const express = require("express");
const router = express.Router();
const db = require("../core/mysql");
const multer = require("multer");


let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "upload/avatar");
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}${file.originalname}`);
  },
});
const upload = multer({ storage });
router.post("/upload", upload.single("file"), async (req, res, next) => {
  // let url = `http://localhost:8889/upload/avatar/${req.file.filename}`;
  let filePath = `http://110.40.132.203:8089/images/${req.file.filename}`;

  // const filePath = path.join(
  //   __dirname.split("src")[0],
  //   "/upload/avatar",
  //   req.file.filename
  // );
  let userId = req.body.avatarId;
  console.log("---req---", filePath);
  console.log("---userId---", userId);
  if (!req.file || !req.body.avatarId) {
    return res.json({
      code: 500,
      msg: "未携带userid或无上传文件",
    });
  } else {
    const avatarSql = `UPDATE userdata SET avatar='${filePath}'  WHERE userid='${userId}';`;
    db.query(avatarSql, (err, result) => {
      if (err) res.json({ code: 500, msg: "上传失败" });
      res.json({
        code: 200,
        msg: "上传成功",
        url: filePath,
      });
    });
  }
});
module.exports = router;
